package com.wenqiner.requesttool.view.base;

import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;

import java.util.HashSet;
import java.util.Set;

/**
 * @author rhf
 * @date 2023-03-02
 **/
public class AbstractRequestLayout {

    /**
     * 创建header/system parameter表格
     *
     * @param gridPane 表格组建
     * @param rowIndex 行值
     * @author rhf
     */
    protected void createTable(GridPane gridPane, int rowIndex) {
        TextField tableKey = new TextField();
        TextField tableValue = new TextField();
        Button btn = new Button("-");
        gridPane.addRow(rowIndex, tableKey, tableValue, btn);

        int finalRowCount = rowIndex;
        btn.setOnAction(e -> {
            deleteRow(gridPane, finalRowCount);
        });
    }


    /**
     * 删除表格
     *
     * @param gridPane 表格组建
     * @param rowCount 行数
     * @author rhf
     */
    protected void deleteRow(GridPane gridPane, int rowCount) {
        Set<Node> deleteNodes = new HashSet<>();
        for (Node child : gridPane.getChildren()) {
            // get index from child
            Integer rowIndex = GridPane.getRowIndex(child);
            // handle null values for index=0
            int r = rowIndex == null ? 0 : rowIndex;
            if (r == rowCount) {
                deleteNodes.add(child);
            }
        }
        gridPane.getChildren().removeAll(deleteNodes);
    }

    /**
     * 获取当前gridPane最大行的下一行的值，+1会重叠
     *
     * @param gridPane gridPane
     * @return java.lang.Integer
     * @author rhf
     */
    protected Integer gridPaneNextRowNum(GridPane gridPane) {
        return maxGridPaneRow(gridPane) + 2;
    }

    /**
     * 获取当前gridPane最大的行号
     *
     * @param gridPane gridPane
     * @return java.lang.Integer
     * @author rhf
     */
    protected Integer maxGridPaneRow(GridPane gridPane) {
        Set<Integer> noteRowNum = new HashSet<>();
        for (Node child : gridPane.getChildren()) {
            // get index from child
            Integer rowIndex = GridPane.getRowIndex(child);
            // handle null values for index=0
            int r = rowIndex == null ? 0 : rowIndex;
            noteRowNum.add(r);
        }
        return noteRowNum.stream()
                .reduce((acc, i) -> acc > i ? acc : i)
                .get();
    }
}
